import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Card, Button, Form, Input, Table, Popconfirm, message } from "antd";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
  WarningOutlined,
} from "@ant-design/icons";
import {
  reqGetHospitalListApi,
  reqDeleteHospitalSetApi,
  reqDeleteHospitalSetCheckedApi,
} from "@api/hospital";
import type { ColumnsType } from "antd/es/table";
import type {
  HospitalList,
  HospitalListItem,
} from "@api/hospital/model/hospitalListType";

// 标示是否点击了查询按钮
let flag = false;
let hospitalId = 0;

export default function HospitalSet() {
  // 编程导航
  const navigate = useNavigate();
  // 创建表单实例
  const [form] = Form.useForm();
  // 定义hospitalList数据
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(3);
  const [total, setTotal] = useState(0);
  const [hospitalList, setHospitalList] = useState<HospitalList>([]);

  // 批量删除按钮的禁用标识
  const [disabled, setDisabled] = useState(true);
  // 批量删除的id列表
  const [delIdList, setDelIdList] = useState<React.Key[]>([]);

  // 模拟组件挂载钩子 挂载时获取分页列表
  useEffect(() => {
    getHospitalList(page, pageSize);
  }, []);

  // 请求医院列表数据
  async function getHospitalList(page: number, pageSize: number) {
    let res;
    if (flag) {
      // 带查询条件
      // 从表单实例身上读取值
      const { hosname, hoscode } = form.getFieldsValue();
      res = await reqGetHospitalListApi(page, pageSize, hosname, hoscode);
    } else {
      // 不带查询条件
      res = await reqGetHospitalListApi(page, pageSize);
    }
    setHospitalList(res.records);
    setTotal(res.total);
  }
  // 点击查询
  function onFinish(values: any) {
    flag = true;
    getHospitalList(1, pageSize);
  }
  // 清空查询条件
  function clearBtn() {
    flag = false;
    form.resetFields();
    setPage(1);
    getHospitalList(1, pageSize);
  }

  // 删除一个
  async function deleteOne() {
    await reqDeleteHospitalSetApi(hospitalId);
    message.success("删除成功");
    hospitalId = 0;
    getHospitalList(page, pageSize);
  }
  // 批量删除
  async function deleteChecked() {
    await reqDeleteHospitalSetCheckedApi(delIdList);
    message.success("删除成功");
    setDelIdList([]);
    setDisabled(true);
    getHospitalList(page, pageSize);
  }
  function cancel() {
    message.error("取消操作");
  }

  // hospitalList表格结构
  const columns: ColumnsType<HospitalListItem> = [
    {
      title: "序号",
      render(value, record, index) {
        return index + 1;
      },
      width: 80,
      align: "center",
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机号",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      render: (value, record, index) => (
        <>
          <Button
            type="primary"
            icon={<EditOutlined />}
            style={{ marginRight: 10 }}
            onClick={() => {
              navigate(`/syt/hospital/hospitalset/edit/${record.id}`);
            }}
          ></Button>
          {/* 删除确认框 */}
          <Popconfirm
            icon={<WarningOutlined />}
            title="您确定要删除该医院设置吗?"
            onConfirm={deleteOne}
            onCancel={cancel}
            okText="确定"
            okType="danger"
            cancelText="取消"
          >
            <Button
              onClick={() => {
                // 保存当前医院id
                hospitalId = record.id as number;
              }}
              type="primary"
              danger
              icon={<DeleteOutlined />}
            ></Button>
          </Popconfirm>
        </>
      ),
      width: 120,
      align: "center",
      // 固定列
      fixed: "right",
    },
  ];

  return (
    <Card>
      {/* form={form} 绑定表单实例 方便获取表单数据 */}
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 20 }}
        onFinish={onFinish}
      >
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={clearBtn}>清空</Button>
        </Form.Item>
      </Form>
      <Button
        type="primary"
        htmlType="submit"
        style={{ marginRight: 20 }}
        onClick={() => {
          navigate("/syt/hospital/hospitalset/add");
        }}
      >
        添加
      </Button>
      <Popconfirm
        icon={<WarningOutlined />}
        title="您确定要删除该医院设置吗?"
        onConfirm={deleteChecked}
        onCancel={cancel}
        okText="确定"
        okType="danger"
        cancelText="取消"
      >
        <Button disabled={disabled} type="primary" danger>
          批量删除
        </Button>
      </Popconfirm>

      <Table
        bordered
        style={{ marginTop: 20 }}
        scroll={{ x: 1400 }}
        dataSource={hospitalList}
        columns={columns}
        rowKey="id"
        // 分页器相关
        pagination={{
          current: page,
          total,
          pageSize,
          // 每页显示多少条的下拉框
          showSizeChanger: true,
          // 跳转到哪一页的输入框
          showQuickJumper: true,
          // 显示总数
          showTotal(total, range) {
            return `总共： ${total} 条`;
          },
          // 设置每页多少条下拉框的选项
          pageSizeOptions: [3, 6, 9, 12],
          // 点击分页器触发的回调
          onChange(page, pageSize) {
            getHospitalList(page, pageSize);
            // 把最新的每页显示条数赋值给state
            setPageSize(pageSize);
            setPage(page);
          },
        }}
        rowSelection={{
          onChange(selectedRowKeys) {
            if (selectedRowKeys.length) {
              setDisabled(false);
              // 收集已选中的医院 ID
              setDelIdList(selectedRowKeys);
            } else {
              setDisabled(true);
            }
          },
        }}
      />
    </Card>
  );
}
